package com.tsmask;

import java.io.IOException;
import java.util.Date;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 网络请求工具
 * 
 * @author TsMask
 *
 */
public class HttpUtil {
 
	OkHttpClient client = new OkHttpClient();
	
	/**
	 * 获取当前位置天气信息
	 */
	public void clockWeather() {
		client = new OkHttpClient(); 
		Request request = new Request.Builder()
				.url("http://weather.hao.360.cn/sed_api_weather_info.php?app=clockWeather&_jsonp=getCityCode").get()
				.addHeader("Accept", "*/*").addHeader("Host", "weather.hao.360.cn").build();
		try {
			Response response = client.newCall(request).execute();
			String result = response.body().string();
			String jsonStr = result.substring(result.indexOf("(") + 1, result.lastIndexOf(")"));
			Main.weatherInfo = (JSONObject) JSONObject.parse(unicodeToUtf8(jsonStr)); 
			response.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 天气查询
	 * 
	 * @param code 城市区域码
	 */
	public void weatherQuery(String code) {
		Long statrTime = new Date().getTime();
		Long endTime = Integer.valueOf(code) + new Date().getTime();
		client = new OkHttpClient(); 
		Request request = new Request.Builder()
				.url("http://tq.360.cn/api/weatherquery/querys?app=tq360&code=" + code + "&t=" + statrTime + "&c="
						+ endTime + "&_jsonp=renderData")
				.get().addHeader("Accept", "*/*").addHeader("Host", "tq.360.cn").build();
		try {
			Response response = client.newCall(request).execute();
			if(response.isSuccessful()) {
				String result = response.body().string();
				String jsonStr = result.substring(result.indexOf("(") + 1, result.lastIndexOf(")"));
				Main.weatherInfo = (JSONObject) JSONObject.parse(unicodeToUtf8(jsonStr)); 
			}
			response.close();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			System.exit(0);
		}
	}

	/**
	 * 区域位置查询
	 * 
	 * @param grade 城市域级 province city town
	 * @param code  城市区域码
	 */
	public void areaQuery(String grade, String code) {
		String url = "http://cdn.weather.hao.360.cn/sed_api_area_query.php?grade=" + grade + "&_jsonp=loadData";
		// 非空时选择城市地区码
		if (code != null)
			url += "&code=" + code;
		client = new OkHttpClient(); 
		Request request = new Request.Builder().url(url).get().build();
		try {
			Response response = client.newCall(request).execute();
			String result = response.body().string();
			String jsonStr = result.substring(result.indexOf("(") + 1, result.lastIndexOf(")"));
			if (code == null)
				Main.provinceArray = (JSONArray) JSONArray.parse(unicodeToUtf8(jsonStr));
			if ("city".equals(grade))
				Main.cityArray = (JSONArray) JSONArray.parse(unicodeToUtf8(jsonStr));
			if ("town".equals(grade))
				Main.townArray = (JSONArray) JSONArray.parse(unicodeToUtf8(jsonStr));
			response.close();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

	/**
	 * unicode 转换成 utf-8
	 * 
	 * @author fanhui
	 * @param theString
	 * @return
	 */
	public String unicodeToUtf8(String theString) {
		char aChar;
		int len = theString.length();
		StringBuffer outBuffer = new StringBuffer(len);
		for (int x = 0; x < len;) {
			aChar = theString.charAt(x++);
			if (aChar == '\\') {
				aChar = theString.charAt(x++);
				if (aChar == 'u') {
					// Read the xxxx
					int value = 0;
					for (int i = 0; i < 4; i++) {
						aChar = theString.charAt(x++);
						switch (aChar) {
						case '0':
						case '1':
						case '2':
						case '3':
						case '4':
						case '5':
						case '6':
						case '7':
						case '8':
						case '9':
							value = (value << 4) + aChar - '0';
							break;
						case 'a':
						case 'b':
						case 'c':
						case 'd':
						case 'e':
						case 'f':
							value = (value << 4) + 10 + aChar - 'a';
							break;
						case 'A':
						case 'B':
						case 'C':
						case 'D':
						case 'E':
						case 'F':
							value = (value << 4) + 10 + aChar - 'A';
							break;
						default:
							throw new IllegalArgumentException("Malformed   \\uxxxx   encoding.");
						}
					}
					outBuffer.append((char) value);
				} else {
					if (aChar == 't')
						aChar = '\t';
					else if (aChar == 'r')
						aChar = '\r';
					else if (aChar == 'n')
						aChar = '\n';
					else if (aChar == 'f')
						aChar = '\f';
					outBuffer.append(aChar);
				}
			} else
				outBuffer.append(aChar);
		}
		return outBuffer.toString();
	}

}
